package com.calefk.util {
    
    import flash.events.IOErrorEvent;
    import flash.events.SecurityErrorEvent;
    import flash.net.URLRequest;
    import flash.display.Loader;
    import flash.events.Event;
    import flash.events.ProgressEvent;

    public class SWFLoader extends FileLoader {
        
        private var mLoader:Loader;
        private var mRequest:URLRequest;

        public function SWFLoader(filePath: String) {
            mLoader = new Loader();
            mRequest = new URLRequest(filePath);
            mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeFile);
            mLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressFile);
            mLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorFile);
            mLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorFile);
            mLoader.load(mRequest);
        }
        
        private function ioErrorFile(event:IOErrorEvent):void {
            trace(":: ERROR -> ioErrorFile : " + event.text);
        }
        
        private function securityErrorFile(event:SecurityError):void {
            trace(":: ERROR -> securityErrorFile : " + event.getStackTrace);            
        }
        
        override protected function completeFile(event:Event):void {
            document = event.currentTarget.content;
            isLoad = true;
            
            cleanEvents();
             
            if (onLoadComplete != null) {
				onLoadComplete(this); 
			}
        }
        
        override protected function progressFile(event:ProgressEvent):void {
            mBytesLoaded = event.bytesLoaded;
            mBytesTotal = event.bytesTotal;
            
            if (onProgress != null) {
                onProgress(mBytesLoaded , mBytesTotal);
            }
        }
        
        private function cleanEvents():void {
  			mLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorFile);
            mLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE , completeFile);
            mLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS , progressFile);
            mLoader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorFile);
        }
		
		override public function clean():void {
            cleanEvents();
            
			mLoader = null;
			mRequest = null;
			document = null;
            
			if (onLoadComplete != null) {
                onLoadComplete = null;
            }
		}
        
    }

}